<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <title>Light Rays Shader — Alien.js</title>

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto+Mono">
    <link rel="stylesheet" href="../assets/css/style.css">

    <script type="module">
        import { BloomCompositeMaterial, Color, ColorManagement, CopyMaterial, GLSL3, Group, LinearSRGBColorSpace, LuminosityMaterial, MathUtils, Mesh, OrthographicCamera, PanelItem, PerspectiveCamera, PlaneGeometry, RawShaderMaterial, RepeatWrapping, Scene, SceneCompositeMaterial, TextureLoader, UI, UnrealBloomBlurMaterial, Vector2, WebGLRenderTarget, WebGLRenderer, brightness, getFullscreenTriangle, getViewSize, ticker } from '../../build/alien.three.js';

        // Based on https://www.youtube.com/watch?v=0D-J_Lbxeeg by akella

        const colors = {
            backgroundColor: 0x060606,
            lightColor: 0x3b5b89
        };

        import smootherstep from '../../src/shaders/modules/smootherstep/smootherstep.glsl.js';

        class GodRays extends Group {
            constructor() {
                super();

                this.initViews();
            }

            initViews() {
                const { time, getTexture } = WorldController;

                const texture = getTexture('perlin_noise.png');
                texture.wrapS = RepeatWrapping;
                texture.wrapT = RepeatWrapping;
                texture.generateMipmaps = false;

                const material = new RawShaderMaterial({
                    glslVersion: GLSL3,
                    uniforms: {
                        tNoise: { value: texture },
                        uLightPosition: { value: new Vector2(-10, 10) },
                        uLightColor: { value: new Color(colors.lightColor) },
                        uScale: { value: 0.2 },
                        uSpeed: { value: 0.05 },
                        uThreshold: { value: 0.2 },
                        uSmoothing: { value: 1 },
                        uTime: time
                    },
                    vertexShader: /* glsl */ `
                        in vec3 position;
                        in vec2 uv;

                        uniform mat4 modelMatrix;
                        uniform mat4 modelViewMatrix;
                        uniform mat4 projectionMatrix;

                        out vec2 vUv;
                        out vec3 vWorldPosition;

                        void main() {
                            vUv = uv;
                            vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;

                            gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
                        }
                    `,
                    fragmentShader: /* glsl */ `
                        precision highp float;

                        uniform sampler2D tNoise;
                        uniform vec2 uLightPosition;
                        uniform vec3 uLightColor;
                        uniform float uScale;
                        uniform float uSpeed;
                        uniform float uThreshold;
                        uniform float uSmoothing;
                        uniform float uTime;

                        in vec2 vUv;
                        in vec3 vWorldPosition;

                        out vec4 FragColor;

                        ${smootherstep}

                        void main() {
                            vec2 godray = vWorldPosition.xy - uLightPosition;
                            float uvDirection = atan(godray.y, godray.x) * uScale;

                            float c1 = texture(tNoise, vec2(uvDirection, 0.0) + 0.05 * uTime * uSpeed).r;
                            float c2 = texture(tNoise, vec2(0.0, uvDirection) + 0.05 * uTime * uSpeed * 1.5).g;
                            float v = min(c1, c2);
                            float alpha = smootherstep(uThreshold, uThreshold + uSmoothing, v);
                            float fade = smootherstep(0.15, 0.86, vUv.y);

                            FragColor = vec4(uLightColor, alpha * fade);
                        }
                    `,
                    transparent: true,
                    depthTest: false,
                    depthWrite: false
                });

                const mesh = new Mesh(
                    new PlaneGeometry(),
                    material
                );
                mesh.renderOrder = -1; // Render first (default is 0)
                this.add(mesh);

                this.material = material;
                this.mesh = mesh;
            }

            // Public methods

            resize = () => {
                const { getViewSize } = WorldController;

                const { x, y } = getViewSize();
                this.mesh.scale.set(x, y, 1);
            };

            update = () => {
            };
        }

        class SceneView extends Group {
            constructor() {
                super();

                this.initViews();
            }

            initViews() {
                this.godrays = new GodRays();
                this.add(this.godrays);
            }

            // Public methods

            resize = () => {
                this.godrays.resize();
            };

            update = () => {
            };
        }

        class SceneController {
            static init(view) {
                this.view = view;
            }

            // Public methods

            static resize = () => {
                this.view.resize();
            };

            static update = () => {
                this.view.update();
            };
        }

        class PanelController {
            static init(scene, view, ui) {
                this.scene = scene;
                this.view = view;
                this.ui = ui;

                this.lastInvert = null;

                this.initPanel();
                this.setInvert(this.scene.background);
            }

            static initPanel() {
                const { luminosityMaterial, bloomCompositeMaterial } = RenderManager;

                const { godrays } = this.view;

                const items = [
                    {
                        name: 'FPS'
                    },
                    {
                        type: 'divider'
                    },
                    {
                        type: 'color',
                        value: this.scene.background,
                        callback: value => {
                            this.scene.background.copy(value);

                            this.setInvert(value);
                        }
                    },
                    {
                        type: 'divider'
                    },
                    {
                        type: 'color',
                        value: godrays.material.uniforms.uLightColor.value,
                        callback: value => {
                            godrays.material.uniforms.uLightColor.value.copy(value);
                        }
                    },
                    {
                        type: 'slider',
                        name: 'X',
                        min: -10,
                        max: 10,
                        step: 0.1,
                        value: godrays.material.uniforms.uLightPosition.value.x,
                        callback: value => {
                            godrays.material.uniforms.uLightPosition.value.x = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Y',
                        min: -10,
                        max: 10,
                        step: 0.1,
                        value: godrays.material.uniforms.uLightPosition.value.y,
                        callback: value => {
                            godrays.material.uniforms.uLightPosition.value.y = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Scale',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: godrays.material.uniforms.uScale.value,
                        callback: value => {
                            godrays.material.uniforms.uScale.value = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Speed',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: godrays.material.uniforms.uSpeed.value,
                        callback: value => {
                            godrays.material.uniforms.uSpeed.value = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Thresh',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: godrays.material.uniforms.uThreshold.value,
                        callback: value => {
                            godrays.material.uniforms.uThreshold.value = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Smooth',
                        min: 0,
                        max: 2,
                        step: 0.01,
                        value: godrays.material.uniforms.uSmoothing.value,
                        callback: value => {
                            godrays.material.uniforms.uSmoothing.value = value;
                        }
                    },
                    {
                        type: 'divider'
                    },
                    {
                        type: 'slider',
                        name: 'Thresh',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: luminosityMaterial.uniforms.uThreshold.value,
                        callback: value => {
                            luminosityMaterial.uniforms.uThreshold.value = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Smooth',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: luminosityMaterial.uniforms.uSmoothing.value,
                        callback: value => {
                            luminosityMaterial.uniforms.uSmoothing.value = value;
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Strength',
                        min: 0,
                        max: 2,
                        step: 0.01,
                        value: RenderManager.bloomStrength,
                        callback: value => {
                            RenderManager.bloomStrength = value;
                            bloomCompositeMaterial.uniforms.uBloomFactors.value = RenderManager.bloomFactors();
                        }
                    },
                    {
                        type: 'slider',
                        name: 'Radius',
                        min: 0,
                        max: 1,
                        step: 0.01,
                        value: RenderManager.bloomRadius,
                        callback: value => {
                            RenderManager.bloomRadius = value;
                            bloomCompositeMaterial.uniforms.uBloomFactors.value = RenderManager.bloomFactors();
                        }
                    }
                ];

                items.forEach(data => {
                    this.ui.addPanel(new PanelItem(data));
                });
            }

            // Public methods

            static setInvert = value => {
                // Light colour is inverted
                const invert = brightness(value) > 0.6;

                if (invert !== this.lastInvert) {
                    this.lastInvert = invert;

                    this.ui.invert(invert);
                }
            };
        }

        const BlurDirectionX = new Vector2(1, 0);
        const BlurDirectionY = new Vector2(0, 1);

        class RenderManager {
            static init(renderer, scene, camera) {
                this.renderer = renderer;
                this.scene = scene;
                this.camera = camera;

                // Unreal bloom
                this.luminosityThreshold = 0;
                this.luminositySmoothing = 1;
                this.bloomStrength = 1;
                this.bloomRadius = 1;

                this.enabled = true;

                this.initRenderer();
            }

            static initRenderer() {
                const { screenTriangle } = WorldController;

                this.renderer.autoClear = false;

                // Fullscreen triangle
                this.screenCamera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
                this.screen = new Mesh(screenTriangle);
                this.screen.frustumCulled = false;

                // Render targets
                this.renderTargetA = new WebGLRenderTarget(1, 1, {
                    depthBuffer: false
                });

                this.renderTargetB = this.renderTargetA.clone();

                this.renderTargetBright = this.renderTargetA.clone();
                this.renderTargetsHorizontal = [];
                this.renderTargetsVertical = [];
                this.nMips = 5;

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.renderTargetsHorizontal.push(this.renderTargetA.clone());
                    this.renderTargetsVertical.push(this.renderTargetA.clone());
                }

                // Luminosity high pass material
                this.luminosityMaterial = new LuminosityMaterial();
                this.luminosityMaterial.uniforms.uThreshold.value = this.luminosityThreshold;
                this.luminosityMaterial.uniforms.uSmoothing.value = this.luminositySmoothing;

                // Separable Gaussian blur materials
                this.blurMaterials = [];

                const kernelSizeArray = [3, 5, 7, 9, 11];

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.blurMaterials.push(new UnrealBloomBlurMaterial(kernelSizeArray[i]));
                }

                // Unreal bloom composite material
                this.bloomCompositeMaterial = new BloomCompositeMaterial({ dithering: true });
                this.bloomCompositeMaterial.uniforms.tBlur1.value = this.renderTargetsVertical[0].texture;
                this.bloomCompositeMaterial.uniforms.tBlur2.value = this.renderTargetsVertical[1].texture;
                this.bloomCompositeMaterial.uniforms.tBlur3.value = this.renderTargetsVertical[2].texture;
                this.bloomCompositeMaterial.uniforms.tBlur4.value = this.renderTargetsVertical[3].texture;
                this.bloomCompositeMaterial.uniforms.tBlur5.value = this.renderTargetsVertical[4].texture;
                this.bloomCompositeMaterial.uniforms.uBloomFactors.value = this.bloomFactors();

                // Composite material
                this.compositeMaterial = new SceneCompositeMaterial({ dithering: true });

                // Copy material
                this.copyMaterial = new CopyMaterial();
            }

            static bloomFactors() {
                const bloomFactors = [1, 0.8, 0.6, 0.4, 0.2];

                for (let i = 0, l = this.nMips; i < l; i++) {
                    const factor = bloomFactors[i];
                    bloomFactors[i] = this.bloomStrength * MathUtils.lerp(factor, 1.2 - factor, this.bloomRadius);
                }

                return bloomFactors;
            }

            // Public methods

            static resize = (width, height, dpr) => {
                this.renderer.setPixelRatio(dpr);
                this.renderer.setSize(width, height);

                width = Math.round(width * dpr);
                height = Math.round(height * dpr);

                this.renderTargetA.setSize(width, height);
                this.renderTargetB.setSize(width, height);

                // Unreal bloom
                width = Math.round(width / 2);
                height = Math.round(height / 2);

                this.renderTargetBright.setSize(width, height);

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.renderTargetsHorizontal[i].setSize(width, height);
                    this.renderTargetsVertical[i].setSize(width, height);

                    this.blurMaterials[i].uniforms.uResolution.value.set(width, height);

                    width = Math.round(width / 2);
                    height = Math.round(height / 2);
                }
            };

            static update = () => {
                const renderer = this.renderer;
                const scene = this.scene;
                const camera = this.camera;

                if (!this.enabled) {
                    renderer.setRenderTarget(null);
                    renderer.clear();
                    renderer.render(scene, camera);
                    return;
                }

                const renderTargetA = this.renderTargetA;
                const renderTargetB = this.renderTargetB;
                const renderTargetBright = this.renderTargetBright;
                const renderTargetsHorizontal = this.renderTargetsHorizontal;
                const renderTargetsVertical = this.renderTargetsVertical;

                // Scene pass
                renderer.setRenderTarget(renderTargetA);
                renderer.clear();
                renderer.render(scene, camera);

                // Copy pass
                this.copyMaterial.uniforms.tMap.value = renderTargetA.texture;
                this.screen.material = this.copyMaterial;
                renderer.setRenderTarget(renderTargetB);
                renderer.render(this.screen, this.screenCamera);

                // Extract bright areas
                this.luminosityMaterial.uniforms.tMap.value = renderTargetB.texture;
                this.screen.material = this.luminosityMaterial;
                renderer.setRenderTarget(renderTargetBright);
                renderer.clear();
                renderer.render(this.screen, this.screenCamera);

                // Blur all the mips progressively
                let inputRenderTarget = renderTargetBright;

                for (let i = 0, l = this.nMips; i < l; i++) {
                    this.screen.material = this.blurMaterials[i];

                    this.blurMaterials[i].uniforms.tMap.value = inputRenderTarget.texture;
                    this.blurMaterials[i].uniforms.uDirection.value = BlurDirectionX;
                    renderer.setRenderTarget(renderTargetsHorizontal[i]);
                    renderer.clear();
                    renderer.render(this.screen, this.screenCamera);

                    this.blurMaterials[i].uniforms.tMap.value = this.renderTargetsHorizontal[i].texture;
                    this.blurMaterials[i].uniforms.uDirection.value = BlurDirectionY;
                    renderer.setRenderTarget(renderTargetsVertical[i]);
                    renderer.clear();
                    renderer.render(this.screen, this.screenCamera);

                    inputRenderTarget = renderTargetsVertical[i];
                }

                // Composite all the mips
                this.screen.material = this.bloomCompositeMaterial;
                renderer.setRenderTarget(renderTargetsHorizontal[0]);
                renderer.clear();
                renderer.render(this.screen, this.screenCamera);

                // Composite pass (render to screen)
                this.compositeMaterial.uniforms.tScene.value = renderTargetB.texture;
                this.compositeMaterial.uniforms.tBloom.value = renderTargetsHorizontal[0].texture;
                this.screen.material = this.compositeMaterial;
                renderer.setRenderTarget(null);
                renderer.clear();
                renderer.render(this.screen, this.screenCamera);
            };
        }

        class WorldController {
            static init() {
                this.initWorld();
                this.initLights();
                this.initLoaders();

                this.addListeners();
            }

            static initWorld() {
                this.renderer = new WebGLRenderer({
                    powerPreference: 'high-performance',
                    antialias: true
                });

                // Output canvas
                this.element = this.renderer.domElement;

                // Disable color management
                ColorManagement.enabled = false;
                this.renderer.outputColorSpace = LinearSRGBColorSpace;

                // 3D scene
                this.scene = new Scene();
                this.scene.background = new Color(colors.backgroundColor);
                this.camera = new PerspectiveCamera(30);
                this.camera.near = 0.5;
                this.camera.far = 40;
                this.camera.position.z = 8;
                this.camera.lookAt(this.scene.position);

                // Global geometries
                this.screenTriangle = getFullscreenTriangle();

                // Global uniforms
                this.resolution = { value: new Vector2() };
                this.texelSize = { value: new Vector2() };
                this.aspect = { value: 1 };
                this.time = { value: 0 };
                this.frame = { value: 0 };

                // Global settings
                this.anisotropy = this.renderer.capabilities.getMaxAnisotropy();
            }

            static initLights() {
            }

            static initLoaders() {
                this.textureLoader = new TextureLoader();
                this.textureLoader.setPath('../assets/textures/');
            }

            static addListeners() {
                this.renderer.domElement.addEventListener('touchstart', this.onTouchStart);
            }

            // Event handlers

            static onTouchStart = e => {
                e.preventDefault();
            };

            // Public methods

            static resize = (width, height, dpr) => {
                this.camera.aspect = width / height;
                this.camera.updateProjectionMatrix();

                width = Math.round(width * dpr);
                height = Math.round(height * dpr);

                this.resolution.value.set(width, height);
                this.texelSize.value.set(1 / width, 1 / height);
                this.aspect.value = width / height;
            };

            static update = (time, delta, frame) => {
                this.time.value = time;
                this.frame.value = frame;
            };

            // Global handlers

            static getTexture = (path, callback) => this.textureLoader.load(path, callback);

            static loadTexture = path => this.textureLoader.loadAsync(path);

            static getViewSize = object => getViewSize(this.camera, object);
        }

        class App {
            static async init() {
                this.initWorld();
                this.initViews();
                this.initControllers();

                this.addListeners();
                this.onResize();

                this.initPanel();
            }

            static initWorld() {
                WorldController.init();
                document.body.appendChild(WorldController.element);
            }

            static initViews() {
                this.view = new SceneView();
                WorldController.scene.add(this.view);

                this.ui = new UI({ fps: true });
                this.ui.animateIn();
                document.body.appendChild(this.ui.element);
            }

            static initControllers() {
                const { renderer, scene, camera } = WorldController;

                SceneController.init(this.view);
                RenderManager.init(renderer, scene, camera);
            }

            static initPanel() {
                const { scene } = WorldController;

                PanelController.init(scene, this.view, this.ui);
            }

            static addListeners() {
                window.addEventListener('resize', this.onResize);
                ticker.add(this.onUpdate);
                ticker.start();
            }

            // Event handlers

            static onResize = () => {
                const width = document.documentElement.clientWidth;
                const height = document.documentElement.clientHeight;
                const dpr = window.devicePixelRatio;

                WorldController.resize(width, height, dpr);
                SceneController.resize();
                RenderManager.resize(width, height, dpr);
            };

            static onUpdate = (time, delta, frame) => {
                WorldController.update(time, delta, frame);
                SceneController.update();
                RenderManager.update(time, delta, frame);
                this.ui.update();
            };
        }

        App.init();
    </script>
</head>
<body>
</body>
</html>
